package com.sgb.merchant.view.activity;

import android.content.Intent;
import android.text.TextUtils;
import android.util.TypedValue;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.fondesa.recyclerviewdivider.DividerDecoration;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener;
import com.sgb.link.entity.EventConstant;
import com.sgb.link.entity.MainEvent;
import com.sgb.link.entity.merchant.DynamicListEntity;
import com.sgb.link.entity.merchant.PublishIndustryEntity;
import com.sgb.link.router.PathMerchant;
import com.sgb.link.utils.EntityConversion;
import com.sgb.merchant.R;
import com.sgb.merchant.databinding.MerchantActivitySelfDynamicBinding;
import com.sgb.merchant.view.adapter.SelfDynamicAdapter;
import com.sgb.merchant.viewmodel.IndustryViewModel;
import com.sgb.net.entity.ListResponse;
import com.swgk.core.base.model.entity.RouterKey;
import com.swgk.core.common.base.BaseActivity;
import com.swgk.core.dialog.RoundDialog;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.List;

/**
 * @author: 王彬臣
 * @date: 2021/10/14
 * @Description: 发布动态列表
 */
@Route(path = PathMerchant.SelfDynamicActivity)
public class SelfDynamicActivity extends BaseActivity<IndustryViewModel, MerchantActivitySelfDynamicBinding> {

    @Autowired(name = RouterKey.DATA)
    PublishIndustryEntity mEntity;

    @Autowired(name = RouterKey.DATA1)
    ArrayList<String> logoList;

    @Autowired(name = RouterKey.DATA2)
    ArrayList<String> urlList;

    @Autowired(name = RouterKey.BOOLEAN, desc = "是否来着我的页面")
    boolean isSelf = false;

    SelfDynamicAdapter mAdapter;

    List<DynamicListEntity> mList=new ArrayList<>();

    String industrialParkNo="";
    private int selectPosition;

    @Override
    protected int layoutId() {
        return R.layout.merchant_activity_self_dynamic;
    }

    @Override
    protected void createViewModel() {
        mViewModel=new ViewModelProvider(this).get(IndustryViewModel.class);

    }

    @Override
    protected void init() {
        ARouter.getInstance().inject(this);
        if(!TextUtils.isEmpty(mEntity.getNo())){
            mBinding.actionBar.setTitle("编辑产业园区");
            industrialParkNo=mEntity.getNo();
        }

        if(TextUtils.isEmpty(industrialParkNo)){
            mBinding.refreshLayout.setEnableLoadMore(false);
            mBinding.refreshLayout.setEnableRefresh(false);
            if(mEntity.getImIndustrialParkTrendsList()!=null&&mEntity.getImIndustrialParkTrendsList().size()>0){
                for(PublishIndustryEntity.ImIndustrialParkTrendsListBean data:mEntity.getImIndustrialParkTrendsList()){
                    DynamicListEntity dynamic=EntityConversion.modelA2B(data,DynamicListEntity.class);
                    mList.add(dynamic);
                }
            }
        }else{
             mBinding.refreshLayout.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
                @Override
                public void onLoadMore(@NonNull @NotNull RefreshLayout refreshLayout) {
                    getData(true);
                }

                @Override
                public void onRefresh(@NonNull @NotNull RefreshLayout refreshLayout) {
                    getData(false);
                }
            });
            mViewModel.ldDynamic.observe(this,this::syncData);
            getData(false);
        }
        mBinding.setOnClick(this);
        mBinding.actionBar.setOnBackClickListener(this);
        mBinding.actionBar.setMenuFunctionClick(this);
        mBinding.recycler.setLayoutManager(new LinearLayoutManager(this));
        DividerDecoration.builder(this)
                .color(getResources().getColor(R.color.color_f5f5f5))
                .size(10, TypedValue.COMPLEX_UNIT_DIP)
                .build()
                .addTo(mBinding.recycler);

        mAdapter=new SelfDynamicAdapter(mList);
        mAdapter.bindToRecyclerView(mBinding.recycler);
        mAdapter.setClickBtnListener(new SelfDynamicAdapter.ClickBtnListener() {
            @Override
            public void editClick(DynamicListEntity entity, int position) {
                selectPosition=position;
                ARouter.getInstance().build(PathMerchant.EditDynamicActivity).
                        withString(RouterKey.NO,mEntity.getNo()).withSerializable(RouterKey.DATA,mList.get(position)).
                        withBoolean(RouterKey.BOOLEAN,true).
                        navigation(SelfDynamicActivity.this,1000);

            }

            @Override
            public void delClick(String no, int position) {
                selectPosition=position;
                new RoundDialog.Builder(SelfDynamicActivity.this)
                        .title("温馨提示")
                        .content("请问是否确认删除？")
                        .cancel("取消")
                        .confirm("确定")
                        .cancelable(false)
                        .confirmCallback(v12 -> {
                            if(TextUtils.isEmpty(no)){
                                mList.remove(position);
                                mEntity.getImIndustrialParkTrendsList().remove(position);
                                mAdapter.notifyDataSetChanged();
                            }else{
                                mViewModel.delParkTrends(no);
                            }
                        }).show();


            }
        });
        mAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                   ARouter.getInstance().build(PathMerchant.DynamicDetailActivity).withSerializable(RouterKey.DATA,mList.get(position)).navigation();
            }
        });
        mBinding.recycler.setAdapter(mAdapter);
        mAdapter.setEmptyView(R.layout.merchant_empty_views);
        mViewModel.ldDel.observe(this,success->{
            mList.remove(selectPosition);
            mAdapter.notifyDataSetChanged();
        });


    }
    public void getData(boolean isLoadMore){
        mViewModel.getDynamicList(industrialParkNo,isLoadMore);
    }
    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.right_view_red) {
            ARouter.getInstance().build(PathMerchant.EditDynamicActivity).withString(RouterKey.NO,mEntity.getNo()).navigation(SelfDynamicActivity.this,1000);
        } else if (id == R.id.iv_back_red) {
            finish();
        } else if (id == R.id.tv_last_page) {
            Intent intent = new Intent();
            intent.putExtra("info", mEntity);
            setResult(RESULT_OK, intent);
            finish();
        } else if (id == R.id.tv_next) {
            ARouter.getInstance().build(PathMerchant.MerchantActivityPublishRequire).withSerializable(RouterKey.DATA,mEntity).withBoolean(RouterKey.BOOLEAN,isSelf).
                    withStringArrayList(RouterKey.DATA1,logoList).withStringArrayList(RouterKey.DATA2,urlList).navigation(this,1100);

        }
    }
    /**
     * 产业园区动态数据
     *
     * @param
     */
    public void syncData(ListResponse<List<DynamicListEntity>> entity) {
        mBinding.refreshLayout.finishRefresh();
        mBinding.refreshLayout.finishLoadMore();
        if (mViewModel.dynamicPage == 1) {
            mList.clear();
            mEntity.getImIndustrialParkTrendsList().clear();
        }
        if (entity.getList() != null) {
            mList.addAll(entity.getList());
            for(DynamicListEntity dynamicListEntity : mList) {
                PublishIndustryEntity.ImIndustrialParkTrendsListBean parkTrendsListBean = EntityConversion.modelA2B(dynamicListEntity, PublishIndustryEntity.ImIndustrialParkTrendsListBean.class);
                mEntity.getImIndustrialParkTrendsList().add(parkTrendsListBean);
            }
        }
        mAdapter.notifyDataSetChanged();
        //
        if (entity.getCurrentPage() < entity.getTotalPage()) {
            mBinding.refreshLayout.resetNoMoreData();
        } else {
            mBinding.refreshLayout.finishLoadMoreWithNoMoreData();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable @org.jetbrains.annotations.Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode==1000){
            if(data==null){
                return;
            }
            DynamicListEntity dynamicListEntity= (DynamicListEntity) data.getSerializableExtra("info");
            boolean isEdit=data.getBooleanExtra(RouterKey.BOOLEAN,false);
            if(dynamicListEntity!=null) {
                PublishIndustryEntity.ImIndustrialParkTrendsListBean parkTrendsListBean= EntityConversion.modelA2B(dynamicListEntity, PublishIndustryEntity.ImIndustrialParkTrendsListBean.class);
                if(!isEdit) {
                    mList.add(0, dynamicListEntity);
                    mEntity.getImIndustrialParkTrendsList().add(0,parkTrendsListBean);
                }else{
                    mList.remove(selectPosition);
                    mList.add(selectPosition, dynamicListEntity);
                    mEntity.getImIndustrialParkTrendsList().remove(selectPosition);
                    mEntity.getImIndustrialParkTrendsList().add(selectPosition,parkTrendsListBean);
                }

            }

            mAdapter.notifyDataSetChanged();
        } else if(requestCode==1100){
                if(data==null){
                    setResult(RESULT_OK);
                    finish();
                }
            if(data!=null&&data.getSerializableExtra("info")!=null) {
                mEntity = (PublishIndustryEntity) data.getSerializableExtra("info");
            }
        }
    }
    @Override
    public boolean isUseEventBus() {
        return true;
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(MainEvent event) {
        if (event.getMessageTag() == EventConstant.EVENT_MERCHANT_SELF_INDUSTRY_REFRESH2) {
             mBinding.refreshLayout.autoRefresh();
        }
    }
}
